using System;
using System.Threading;
using System.Threading.Tasks;
using RTMP.SimpleClient;
using RTMP.SimpleClient.Callbacks;
using RTMP.SimpleClient.Messages;

namespace RTMP.SimpleClient.Examples
{
    /// <summary>
    /// 演示如何使用RTMP客户端的回调功能
    /// </summary>
    public class CallbackExample
    {
        /// <summary>
        /// 运行回调示例
        /// </summary>
        public static async Task RunExample()
        {
            Console.WriteLine("=== RTMP客户端回调功能示例 ===");

            // 创建RTMP客户端实例
            var client = new RTMPSimpleClient();

            try
            {
                // 注册连接响应回调
                RegisterConnectCallback(client);

                // 注册CreateStream响应回调
                RegisterCreateStreamCallback(client);

                // 注册播放状态回调
                RegisterPlayStatusCallback(client);

                // 连接到RTMP服务器
                string serverUrl = "rtmp://182.254.168.213:1935/live";
                await client.ConnectAsync(serverUrl);
                
                Console.WriteLine("已连接到RTMP服务器，等待服务器消息...");

                // 模拟一些操作
                await SimulateRTMPOperations(client);

                // 等待一段时间来接收消息
                await Task.Delay(5000);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"示例执行时发生错误: {ex.Message}");
            }
            finally
            {
                // 清理资源
                try
                {
                    await client.CloseAsync();
                    Console.WriteLine("已断开RTMP连接");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"关闭连接时发生错误: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 注册连接响应回调
        /// </summary>
        private static void RegisterConnectCallback(RTMPSimpleClient client)
        {
            // 使用ActionId = 1.0 注册连接响应回调（connect命令的事务ID通常是1）
            var connectKey = CallbackKey.FromActionId(1.0);

            client.RegisterCallback<ConnectResponseMessage>(connectKey, (message, ct) =>
            {
                Console.WriteLine($"=== 收到连接响应 ===");
                Console.WriteLine($"命令: {message.CommandName}");
                Console.WriteLine($"事务ID: {message.TransactionId}");
                Console.WriteLine($"连接状态: {(message.IsConnected ? "成功" : "失败")}");
                
                if (message.ConnectionInfo != null)
                {
                    Console.WriteLine("连接信息:");
                    foreach (var info in message.ConnectionInfo)
                    {
                        Console.WriteLine($"  {info.Key}: {info.Value}");
                    }
                }
                Console.WriteLine();

                return Task.CompletedTask;
            }, isOneTime: true, timeout: TimeSpan.FromSeconds(10));
        }

        /// <summary>
        /// 注册CreateStream响应回调
        /// </summary>
        private static void RegisterCreateStreamCallback(RTMPSimpleClient client)
        {
            // 使用ActionId = 2.0 注册CreateStream响应回调（createStream命令的事务ID通常是2）
            var createStreamKey = CallbackKey.FromActionId(2.0);

            client.RegisterCallback<CreateStreamResponseMessage>(createStreamKey, (message, ct) =>
            {
                Console.WriteLine($"=== 收到CreateStream响应 ===");
                Console.WriteLine($"命令: {message.CommandName}");
                Console.WriteLine($"事务ID: {message.TransactionId}");
                Console.WriteLine($"新流ID: {message.NewStreamId}");
                Console.WriteLine();

                return Task.CompletedTask;
            }, isOneTime: true, timeout: TimeSpan.FromSeconds(5));
        }

        /// <summary>
        /// 注册播放状态回调
        /// </summary>
        private static void RegisterPlayStatusCallback(RTMPSimpleClient client)
        {
            // 使用命令名称注册onStatus回调
            var playStatusKey = CallbackKey.FromCommand("onStatus");

            client.RegisterCallback<PlayStatusMessage>(playStatusKey, (message, ct) =>
            {
                Console.WriteLine($"=== 收到播放状态消息 ===");
                Console.WriteLine($"代码: {message.Code}");
                Console.WriteLine($"级别: {message.Level}");
                Console.WriteLine($"描述: {message.Description}");
                Console.WriteLine($"时间戳: {message.Timestamp}");
                Console.WriteLine($"流ID: {message.StreamId}");
                
                if (message.Details != null)
                {
                    Console.WriteLine("详细信息:");
                    foreach (var detail in message.Details)
                    {
                        Console.WriteLine($"  {detail.Key}: {detail.Value}");
                    }
                }
                Console.WriteLine();

                return Task.CompletedTask;
            }, isOneTime: false); // 播放状态可能会收到多次，所以不设置为一次性
        }

        /// <summary>
        /// 模拟RTMP操作
        /// </summary>
        private static async Task SimulateRTMPOperations(RTMPSimpleClient client)
        {
            try
            {
                Console.WriteLine("开始执行RTMP操作...");

                // 等待连接稳定
                await Task.Delay(1000);

                // 创建流
                Console.WriteLine("创建新流...");
                var streamId = await client.CreateStreamAsync();
                Console.WriteLine($"创建了流ID: {streamId}");

                // 等待CreateStream响应
                await Task.Delay(1000);

                // 开始播放
                Console.WriteLine("开始播放流...");
                await client.PlayAsync(streamId, "test");

                Console.WriteLine("RTMP操作完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"执行RTMP操作时发生错误: {ex.Message}");
            }
        }
    }

    /// <summary>
    /// 自定义消息处理器示例
    /// </summary>
    public class CustomCommandHandler : IMessageCallback<RTMPCommandMessage>
    {
        public Task HandleAsync(RTMPCommandMessage message, CancellationToken cancellationToken = default)
        {
            Console.WriteLine($"=== 自定义处理器收到命令消息 ===");
            Console.WriteLine($"命令: {message.CommandName}");
            Console.WriteLine($"事务ID: {message.TransactionId}");
            
            if (message.CommandObject != null)
            {
                Console.WriteLine("命令对象:");
                foreach (var obj in message.CommandObject)
                {
                    Console.WriteLine($"  {obj.Key}: {obj.Value}");
                }
            }

            if (message.AdditionalInfo != null)
            {
                Console.WriteLine($"附加信息: {message.AdditionalInfo}");
            }

            Console.WriteLine();
            return Task.CompletedTask;
        }
    }

    /// <summary>
    /// 高级回调使用示例
    /// </summary>
    public class AdvancedCallbackExample
    {
        public static async Task RunAdvancedExample()
        {
            Console.WriteLine("=== 高级回调功能示例 ===");

            var client = new RTMPSimpleClient();

            try
            {
                // 注册泛型命令处理器
                var genericKey = CallbackKey.FromActionId(0); // 捕获所有未匹配的消息
                client.RegisterCallback(genericKey, new CustomCommandHandler());

                // 注册基于流ID的回调
                var streamKey = CallbackKey.FromStreamId(1);
                client.RegisterCallback<RTMPCommandMessage>(streamKey, message =>
                {
                    Console.WriteLine($"流ID 1 的消息: {message.CommandName}");
                });

                // 注册复合条件回调
                var compositeKey = new CallbackKey(3.0, 2, "onStatus");
                client.RegisterCallback<PlayStatusMessage>(compositeKey, message =>
                {
                    Console.WriteLine($"精确匹配 - ActionId:3.0, StreamId:2, Command:onStatus");
                    Console.WriteLine($"状态: {message.Code} - {message.Description}");
                });

                await client.ConnectAsync("rtmp://182.254.168.213:1935/live");
                
                Console.WriteLine("高级回调已注册，等待消息...");
                await Task.Delay(3000);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"高级示例执行时发生错误: {ex.Message}");
            }
            finally
            {
                await client.CloseAsync();
            }
        }
    }
}